package com.rear.utils;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonParser.Feature;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class JsonUtil {
	/**
	 * 将JSON数据转换为MAP
	 * @param jsonString
	 * @return
	 */
	public static Map getMap4Json(String jsonString) {   
    	if(jsonString==null || "null".equals(jsonString)){
    		return new HashMap();
    	}
        JSONObject jsonObject = JSONObject.fromObject(jsonString);  
        if(jsonObject==null || jsonObject.isEmpty()){
        	return new HashMap();
        }
        Iterator keyIter = jsonObject.keys();   
        String key;   
        Object value;   
        Map valueMap = new HashMap();   
  
        while (keyIter.hasNext()) {   
            key = (String) keyIter.next();   
            value = jsonObject.get(key);   
            valueMap.put(key, value);   
        }   
  
        return valueMap;   
    }
	
	/**
	 * 将MAP数据转换为JSON
	 * @param map
	 * @return
	 */
    public static String  getJsonForMap(Map map){
    	
    	JSONArray json = JSONArray.fromObject(map);  

    	
    	return json.toString();
    	
    }
    
	 /**  
     * 从json数组中解析出java字符串数组  
     *   
     * @param jsonString  
     * @return  
     */  
    public static String[] getStringArray4Json(String jsonString) {   
        JSONArray jsonArray = JSONArray.fromObject(jsonString);   
        String[] stringArray = new String[jsonArray.size()];   
        for (int i = 0; i < jsonArray.size(); i++) {   
            stringArray[i] = jsonArray.getString(i);   
        }   
  
        return stringArray;   
    } 
 
    /**
     * 将List转换成json串
     * @param list
     * @return
     */
    public static String getJsonFormList(List list){
    	
    	JSONArray jsonarray = JSONArray.fromObject(list);
    	
    	return jsonarray.toString();
    }
    
    
    /**
     * Map , 复合类型bean转成成json
     * @param obj
     * @return
     */
    public static String getJsonFormObj(Object obj){
    	
    	JSONObject jsonObject = JSONObject.fromObject(obj);
    	
    	return jsonObject.toString();
    	
    }
    
    public static final ObjectMapper MAPPER = new ObjectMapper();
    static {
        MAPPER.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
    }

    private static final JsonFactory JSONFACTORY = new JsonFactory();

    /**
     * 转换Java Bean 为 json
     */
    public static String beanToJson(Object o) {
        StringWriter sw = new StringWriter(300);
        JsonGenerator gen = null;
        String result = "";
        try {
            gen = JSONFACTORY.createJsonGenerator(sw);
            MAPPER.writeValue(gen, o);
            result = sw.toString().replaceAll("null", "\"\"");
          
        } catch (Exception e) {
        	e.printStackTrace();
        } finally {
            if (gen != null) {
                try {
                    gen.close();
                } catch (Exception e) {
                }
            }
        }
        return result;
    }
    
    public static <T> T JsontoJavaBean(String content, Class<T> valueType) {
	    try {
	             return MAPPER.readValue(content, valueType);
	         } catch (JsonParseException e) {
	        } catch (JsonMappingException e) {
	             throw new RuntimeException("json字符串转化为 javabean失败" + e.toString());
	        } catch (IOException e) {
	             throw new RuntimeException("json字符串转化为 javabean失败" + e.toString());
	       }
        return null;
     }

    /**
     * 转换Java Bean 为 HashMap
     */
    public static Map<String, Object> beanToMap(Object o) {
        try {
            return MAPPER.readValue(beanToJson(o), HashMap.class);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 转换Json String 为 HashMap
     */
    public static Map<String, Object> jsonToMap(String json, boolean collToString) {
        try {
            Map<String, Object> map = MAPPER.readValue(json, HashMap.class);
            if (collToString) {
                for (Entry<String, Object> entry : map.entrySet()) {
                    if (entry.getValue() instanceof Collection || entry.getValue() instanceof Map) {
                        entry.setValue(beanToJson(entry.getValue()));
                    }
                }
            }
            return map;
        } catch (Exception e) {
            return null;
        }
    }

    @SuppressWarnings("serial")
    public static class JSONParseException extends Exception {
        public JSONParseException(String message) {
            super(message);
        }
    }

    public static String indentJSON(final String jsonIn) throws JSONParseException {
        JsonGenerator gen = null;
        try {
            JsonParser parser = JSONFACTORY.createJsonParser(new StringReader(jsonIn));
            ObjectMapper mapper = new ObjectMapper();
            JsonNode node = null;
            try {
                node = mapper.readTree(parser);
            } catch (JsonParseException ex) {
                throw new JSONParseException(ex.getMessage());
            }
            StringWriter out = new StringWriter();

            // Create pretty printer:
            gen = JSONFACTORY.createJsonGenerator(out);
            gen.useDefaultPrettyPrinter();

            // Now write:
            mapper.writeTree(gen, node);

            return out.toString();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (gen != null) {
                try {
                    gen.flush();
                    gen.close();
                } catch (Exception e) {
                }
            }
        }
        return jsonIn;
    }

    public static String listToJson(List<Map<String, String>> list) {

        JsonGenerator gen = null;
        try {
            StringWriter sw = new StringWriter();
            gen = JSONFACTORY.createJsonGenerator(sw);
            new ObjectMapper().writeValue(gen, list);
            gen.flush();
            return sw.toString();
        } catch (Exception e) {
            return null;
        } finally {
            if (gen != null) {
                try {
                    gen.flush();
                    gen.close();
                } catch (Exception e) {
                }
            }
        }
    }

    public static List<Map<String, String>> jsonToList(String str) {
        try {
            if (StringUtils.isNotBlank(str)) {
                JsonParser parser = JSONFACTORY.createJsonParser(new StringReader(str));

                ArrayList<Map<String, String>> arrList = (ArrayList<Map<String, String>>) new ObjectMapper().readValue(parser, ArrayList.class);
                return arrList;
            } else {
                return null;
            }
        } catch (Exception e) {
            return null;
        }
    }

    /**
    * 将JAVA的MAP转换成JSON字符串，
    * 只转换第一层数据
    * @param map
    * @return
    */
    public static String simpleMapToJsonStr(Map<?, ?> map) {
        if (map == null || map.isEmpty()) {
            return "null";
        }
        String jsonStr = "{";
        Set<?> keySet = map.keySet();
        for (Object key : keySet) {
            jsonStr += "\"" + key + "\":\"" + map.get(key) + "\",";
        }
        jsonStr = jsonStr.substring(0, jsonStr.length() - 1);
        jsonStr += "}";
        return jsonStr;
    }
    
    
    public static<T> T jsonToBean(String content, Class<T> valueType){
    	
    	return (T)JSONObject.toBean(JSONObject.fromObject(content),valueType);
    }
    
public static<T> T jsonToBean(String content, Class<T> valueType,Map<String, Class> classMap){
    	
    	return (T)JSONObject.toBean(JSONObject.fromObject(content),valueType,classMap);
    }

}
